package com.lzb.play.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.lzb.play.R;

import java.io.IOException;

public class SlidingAudioView extends View {
    private static final int REGION_COUNT = 3;
    private Rect[] regions = new Rect[REGION_COUNT];
    private int[] audioResources = new int[REGION_COUNT];
    private MediaPlayer[] mediaPlayers = new MediaPlayer[REGION_COUNT];

    public void setAudioResources(int... resIds) {
        if (resIds.length != REGION_COUNT) {
            throw new IllegalArgumentException("音频资源数量必须等于 " + REGION_COUNT);
        }
        System.arraycopy(resIds, 0, audioResources, 0, REGION_COUNT);
        stopAllAudio();
        releasePlayers();
        init();
    }

    private void releasePlayers() {
        for (MediaPlayer player : mediaPlayers) {
            if (player != null) {
                player.release();
                player = null;
            }
        }
    }

    private int currentRegion = -1;
    private float lastX, lastY;
    private long lastTime;
    private boolean isSliding = false;
    private Paint regionPaint = new Paint();

    public SlidingAudioView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 设置默认音频资源
        if (audioResources[0] == 0) {
            audioResources[0] = R.raw.jiayan;
            audioResources[1] = R.raw.maque;
            audioResources[2] = R.raw.cuiniao;
        }

        for (int i = 0; i < REGION_COUNT; i++) {
            mediaPlayers[i] = MediaPlayer.create(getContext(), audioResources[i]);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        int regionWidth = width / REGION_COUNT;

        // 仅绘制区域边界，不填充颜色和文字
        for (int i = 0; i < REGION_COUNT; i++) {
            regions[i] = new Rect(i * regionWidth, 0, (i + 1) * regionWidth, height);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        long currentTime = System.currentTimeMillis();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                lastTime = currentTime;
                isSliding = false;
                // 按下时不停止音频，让区域切换时处理
                break;

            case MotionEvent.ACTION_MOVE:
                Log.e("TAG", "onTouchEvent: ");
                int newRegion = getRegionIndex(x, y);
                float distance = Math.abs(x - lastX);
                long timeDiff = currentTime - lastTime;
                float speed = distance / Math.max(timeDiff, 1); // 像素/毫秒

                if (newRegion != -1) {
                    if (newRegion != currentRegion) {
                        // 切换区域：停止之前区域的音频，播放新区域音频
                        if (currentRegion != -1) {
                            stopAudio(currentRegion);
                        }
                        float playbackSpeed = calculatePlaybackSpeed(speed);
                        Log.d("SlidingAudioView", "区域切换: " + newRegion + ", 速度: " + speed + ", 播放速度: " + playbackSpeed);
                        playAudio(newRegion, speed);
                        currentRegion = newRegion;
                    } else if (!isSliding) {
                        // 在同一区域开始滑动
                        float playbackSpeed = calculatePlaybackSpeed(speed);
                        Log.d("SlidingAudioView", "开始滑动: " + newRegion + ", 速度: " + speed + ", 播放速度: " + playbackSpeed);
                        playAudio(newRegion, speed);
                    } else {
                        // 同一区域继续滑动，调整播放速度
                        float playbackSpeed = calculatePlaybackSpeed(speed);
                        Log.d("SlidingAudioView", "调整速度: " + speed + " -> " + playbackSpeed);
                        adjustPlaybackSpeed(currentRegion, speed);
                    }
                    isSliding = true;
                }

                lastX = x;
                lastY = y;
                lastTime = currentTime;
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                isSliding = false;
                stopAllAudio();
                currentRegion = -1;
                break;
        }

        return true;
    }

    private int getRegionIndex(float x, float y) {
        for (int i = 0; i < REGION_COUNT; i++) {
            if (regions[i] != null && regions[i].contains((int) x, (int) y)) {
                return i;
            }
        }
        return -1;
    }

    private void playAudio(int regionIndex, float speed) {
        // 确保这个区域的音频已经停止
        stopAudio(regionIndex);

        MediaPlayer player = mediaPlayers[regionIndex];
        if (player == null) {
            player = MediaPlayer.create(getContext(), audioResources[regionIndex]);
            player.setLooping(true);
            mediaPlayers[regionIndex] = player;
        }

        try {
            if (!player.isPlaying()) {
                player.reset();
                player.setDataSource(getContext(),
                        Uri.parse("android.resource://" + getContext().getPackageName() + "/" + audioResources[regionIndex]));
                player.prepare();

                // 根据速度调整播放速度
                float playbackSpeed = calculatePlaybackSpeed(speed);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    player.setPlaybackParams(player.getPlaybackParams().setSpeed(playbackSpeed));
                }

                player.setLooping(true);
                player.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void adjustPlaybackSpeed(int regionIndex, float speed) {
        MediaPlayer player = mediaPlayers[regionIndex];
        if (player.isPlaying()) {
            float playbackSpeed = calculatePlaybackSpeed(speed);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                player.setPlaybackParams(player.getPlaybackParams().setSpeed(playbackSpeed));
            }
        }
    }

    private float calculatePlaybackSpeed(float pixelSpeed) {
        // 将滑动速度转换为播放速度
        float minSpeed = 0.8f;    // 最慢0.8倍速（更慢更悠长）
        float maxSpeed = 5.0f;    // 最快5倍速（更快更急促）

        // 降低阈值，让低速滑动也能感受到变化
        float baseSpeed = 0.1f;   // 基础速度阈值
        float normalizedSpeed = Math.max(0f, Math.min(pixelSpeed, 15f)) / 15f;

        // 使用指数函数让变化更明显
        float exponentialFactor = (float) Math.pow(normalizedSpeed, 0.7f);
        return minSpeed + exponentialFactor * (maxSpeed - minSpeed);
    }

    private void stopAudio(int regionIndex) {
        if (mediaPlayers[regionIndex].isPlaying()) {
            mediaPlayers[regionIndex].pause();
            mediaPlayers[regionIndex].seekTo(0);
        }
    }

    private void stopAllAudio() {
        for (MediaPlayer player : mediaPlayers) {
            if (player.isPlaying()) {
                player.pause();
                player.seekTo(0);
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        for (MediaPlayer player : mediaPlayers) {
            if (player != null) {
                player.release();
            }
        }
    }
}